package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmAddDataService;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.service.dynamic.crm.strategy.CompetitorDynamicStrategy;
import com.xbongbong.paas.service.dynamic.crm.strategy.DynamicStrategyFactory;
import com.xbongbong.paas.service.log.crm.operation.CompetitorAnalysisOperationLogHandler;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.parent.interfaces.logger.OperationLogFactory;
import com.xbongbong.pro.competitor.pojo.dto.log.LinkCompetitorLogDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicLinkOpportunityDTO;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.vo.BeforeSaveVO;
import com.xbongbong.pro.formdata.pojo.vo.SaveVO;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.competitor.CompetitorAnalysisEntity;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CompetitorAnalysisEnum;
import com.xbongbong.saas.model.CompetitorAnalysisModel;
import com.xbongbong.saas.service.CompetitorAnalysisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author: yingjf
 * @date: 2022/8/22 11:15
 * @description: 竞争对手分析
 */
@Slf4j
@Service("competitorAnalysisFormDataService")
public class CompetitorAnalysisFormDataServiceImpl extends AbstractCrmAddDataService {
    @Resource
    private CompetitorAnalysisModel competitorAnalysisModel;
    @Resource
    private DynamicStrategyFactory dynamicStrategyFactory;
    @Resource
    private CompetitorAnalysisService competitorAnalysisService;
    @Resource
    private OperationLogFactory operationLogFactory;

    @Override
    @Deprecated
    public void apiHook(FormDataAddDTO formDataAddDTO, SaveVO saveVO, BeforeSaveVO beforeSaveVO) throws XbbException {

    }

    @Override
    public List<Integer> businessList() {
        return Arrays.asList(XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode());
    }

    @Override
    public SaveVO save(FormDataAddDTO formDataAddDTO, BeforeSaveVO beforeSaveVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity) throws XbbException {
        Long dataId = 0L;
        String corpid = formDataAddDTO.getCorpid();
        Integer saasMark = formDataAddDTO.getSaasMark();
        Integer businessType = formDataAddDTO.getBusinessType();
        try {
            UserVO userVO = getUserName(formDataAddDTO, paasFormDataEntity);
            Integer noApprovalRequired = beforeSaveVO.getNoApprovalRequired();
            if (Objects.equals(1, noApprovalRequired)) {
                CompetitorAnalysisEntity competitorAnalysisEntity = new CompetitorAnalysisEntity();
                BeanUtil.copyProperties(paasFormDataEntity, competitorAnalysisEntity);
                FormDataUtil.removeSystemData(competitorAnalysisEntity.getData());
                JSONObject data = competitorAnalysisEntity.getData();
                // 原始的data不动
                JSONObject cloneData = (JSONObject) CloneUtil.deepClone(data);
                Long competitorId = cloneData.getJSONArray(CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr()).getJSONObject(0).getLong(StringConstant.ID);
                Long customerId = cloneData.getJSONArray(CompetitorAnalysisEnum.CUSTOMER_NAME_HIDE.getAttr()).getJSONObject(0).getLong(StringConstant.ID);
                Long opportunityId = cloneData.getJSONArray(CompetitorAnalysisEnum.OPPORTUNITY_NAME_HIDE.getAttr()).getJSONObject(0).getLong(StringConstant.ID);
                competitorAnalysisEntity.setCompetitorId(competitorId);
                competitorAnalysisEntity.setCustomerId(customerId);
                competitorAnalysisEntity.setOppotunityId(opportunityId);
                cloneData.remove(CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr());
                cloneData.remove(CompetitorAnalysisEnum.CUSTOMER_NAME_HIDE.getAttr());
                cloneData.remove(CompetitorAnalysisEnum.OPPORTUNITY_NAME_HIDE.getAttr());
                competitorAnalysisEntity.setData(cloneData);
                competitorAnalysisModel.insert(competitorAnalysisEntity);
                dataId = competitorAnalysisEntity.getId();
                // 设置属性用于返回
                setPartialAttributes(dataId, null, data, competitorAnalysisEntity.getAddTime(),
                        competitorAnalysisEntity.getUpdateTime(), paasFormDataEntity, beforeSaveVO);
            }
            return new SaveVO(noApprovalRequired, paasFormDataEntity, dataId, userVO);
        } catch (XbbException e) {
            log.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw e;
        } catch (Exception e) {
            log.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }
    }

    @Override
    public void saveRollBack(Long dataId, String corpid, Integer saasMark, Integer businessType) throws XbbException {

    }

    @Override
    public FormDataAddVO afterSave(FormDataAddDTO formDataAddDTO, BeforeSaveVO beforeSaveVO, SaveVO saveVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity) throws XbbException {
        FormDataAddVO formDataAddVO = new FormDataAddVO();
        Long dataId = saveVO.getDataId();
        String corpid = formDataAddDTO.getCorpid();
        Integer saasMark = formDataAddDTO.getSaasMark();
        Integer businessType = formDataAddDTO.getBusinessType();
        try {
            if (Objects.equals(1, saveVO.getNoApprovalRequired())) {
                SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
                BeanUtil.copyProperties(formDataAddDTO, saasFormSaveDTO);
                packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                saasFormSaveDTO.setSaasNeedRedundantAttrPoJo(beforeSaveVO.getSaasNeedRedundantAttrPojo());

                competitorAnalysisService.afterSave(saasFormSaveDTO);
                // 动态保存
                saveDynamic(formDataAddDTO,beforeSaveVO,saveVO);
                // 日志保存
                afterSaveLog(formDataAddDTO,saveVO);
                formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
                formDataAddVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
                formDataAddVO.setDataId(saveVO.getDataId());
                formDataAddVO.setFormDataId(saveVO.getDataId());
            } else {
                formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataAddVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
            }
            return formDataAddVO;
        } catch (Exception e) {
            log.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            saveRollBack(dataId, corpid, saasMark, businessType);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }
    }


    /**
     * 关联竞争对手日志
     * @param formDataAddDTO
     * @param saveVO
     * @throws XbbException
     */
    public  void afterSaveLog(FormDataAddDTO formDataAddDTO,SaveVO saveVO) throws XbbException{

        try {
            LinkCompetitorLogDTO linkCompetitorLogDTO = new LinkCompetitorLogDTO();
            BeanUtil.copyProperties(formDataAddDTO,linkCompetitorLogDTO);

            PaasFormDataEntity paasFormDataEntity = saveVO.getPaasFormDataEntity();
            JSONObject data = paasFormDataEntity.getData();
            Long competitorId = data.getJSONArray(CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr()).getJSONObject(0).getLong(StringConstant.ID);
            Long opportunityId = data.getJSONArray(CompetitorAnalysisEnum.OPPORTUNITY_NAME_HIDE.getAttr()).getJSONObject(0).getLong(StringConstant.ID);

            linkCompetitorLogDTO.setCompetitorId(competitorId);
            linkCompetitorLogDTO.setOpportunityId(opportunityId);

            CompetitorAnalysisOperationLogHandler competitorAnalysisOperationLogHandler = (CompetitorAnalysisOperationLogHandler) operationLogFactory.getOperationLogHandle(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.COMPETITOR_ANALYSIS.getCode());
            if (Objects.nonNull(competitorAnalysisOperationLogHandler)) {
                competitorAnalysisOperationLogHandler.linkCompetitor(linkCompetitorLogDTO);
            }
        }catch (Exception e){
            log.error("CompetitorAnalysisFormDataServiceImpl#afterSaveLog exception :{}",e);
        }

    }

    @Override
    @Deprecated
    public SaveVO saveForWorkflow(FormDataAddDTO formDataAddDTO, BeforeSaveVO beforeSaveVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity) throws XbbException {
        return null;
    }

    @Override
    @Deprecated
    public FormDataAddVO afterSaveForWorkflow(FormDataAddDTO formDataAddDTO, BeforeSaveVO beforeSaveVO, SaveVO saveVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity) throws XbbException {
        return null;
    }

    private void saveDynamic(FormDataAddDTO formDataAddDTO,BeforeSaveVO beforeSaveVO,SaveVO saveVO) throws XbbException {
        try {
            //基本信息获取
            String corpid = formDataAddDTO.getCorpid();
            String userId = formDataAddDTO.getUserId();
            String userName = formDataAddDTO.getLoginUserName();
            PaasFormDataEntity paasFormDataEntity = saveVO.getPaasFormDataEntity();
            JSONObject data = paasFormDataEntity.getData();
            Long competitorId = data.getJSONArray(CompetitorAnalysisEnum.COMPETITOR_NAME_HIDE.getAttr()).getJSONObject(0).getLong(StringConstant.ID);
            Long opportunityId = data.getJSONArray(CompetitorAnalysisEnum.OPPORTUNITY_NAME_HIDE.getAttr()).getJSONObject(0).getLong(StringConstant.ID);
            //封装关联动态对象
            DynamicLinkOpportunityDTO dynamicLinkOpportunityDTO = new DynamicLinkOpportunityDTO();
            dynamicLinkOpportunityDTO.setCompetitorId(competitorId);
            dynamicLinkOpportunityDTO.setUserId(userId);
            dynamicLinkOpportunityDTO.setUserName(userName);
            dynamicLinkOpportunityDTO.setCorpid(corpid);
            dynamicLinkOpportunityDTO.setOpportunityId(opportunityId);

            CompetitorDynamicStrategy competitorDynamicStrategy = dynamicStrategyFactory.getCompetitorDynamicStrategy(ProjectLogEnum.COMPETITOR_CREATE.getSubType());
            competitorDynamicStrategy.linkOpportunity(dynamicLinkOpportunityDTO);
        }catch (Exception e){
            log.error("CompetitorAnalysisFormDataServiceImpl#saveDynamic exception: {}",e);
        }



    }
}
